package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.ApartmentInfoMapper;
import com.atguigu.lease.web.admin.mapper.RoomInfoMapper;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;

    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;


    /**
     * 更新或者新增房间信息，主要还是观察房间id，如果id为空，则为新增，如果id不为空，则为更新
     *
     * @param roomSubmitVo
     * @return
     */
    @Override
    public void saveOrUpdateRoom(RoomSubmitVo roomSubmitVo) {
        //首先，先更新或者新增房间的信息
        RoomInfo roomInfo = new RoomInfo();
        BeanUtils.copyProperties(roomSubmitVo, roomInfo);
        Long id = roomSubmitVo.getId();
        saveOrUpdate(roomInfo);
        //判断是否有id，如果有id，则为更新操作，否则为新增操作
        if (id != null) {
            //更新操作 更新关联信息的数据，由于信息比较多，所以先删除旧数据再新增新的数据
            //删除图片列表信息
            graphInfoService.remove(Wrappers.<GraphInfo>lambdaQuery()
                    .eq(GraphInfo::getItemType, ItemType.ROOM)
                    .eq(GraphInfo::getItemId, id)
            );

            //删除属性关联表信息
            roomAttrValueService.remove(Wrappers.<RoomAttrValue>lambdaQuery()
                    .eq(RoomAttrValue::getRoomId, id)
            );

            //删除配套信息关联表相关信息
            roomFacilityService.remove(Wrappers.<RoomFacility>lambdaQuery()
                    .eq(RoomFacility::getRoomId, id)
            );
            //删除标签信息关联表信息
            roomLabelService.remove(Wrappers.<RoomLabel>lambdaQuery()
                    .eq(RoomLabel::getRoomId, id)
            );
            //删除支付方式关联表信息
            roomPaymentTypeService.remove(Wrappers.<RoomPaymentType>lambdaQuery()
                    .eq(RoomPaymentType::getRoomId, id)
            );
            //删除租期关联表信息
            roomLeaseTermService.remove(Wrappers.<RoomLeaseTerm>lambdaQuery()
                    .eq(RoomLeaseTerm::getRoomId, id)
            );
        }

        //插入新的关联信息
        //获取到房间的id 获取实体类里面的id，因为有可能是新增，所以可能没有id
        Long roomId = roomInfo.getId();
        //1.插入图片信息
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo> graphInfoList = graphVoList.stream().map(s -> {
                GraphInfo graphInfo = new GraphInfo();
                BeanUtils.copyProperties(s, graphInfo);
                //补充信息
                graphInfo.setItemType(ItemType.ROOM);
                graphInfo.setItemId(roomId);
                return graphInfo;
            }).collect(Collectors.toList());
            graphInfoService.saveBatch(graphInfoList);
        }

        //2.插入属性信息
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIds)) {
            List<RoomAttrValue> roomAttrValueList = attrValueIds.stream().map(s -> {
                RoomAttrValue roomAttrValue = new RoomAttrValue();
                roomAttrValue.setRoomId(roomId);
                roomAttrValue.setAttrValueId(s);
                return roomAttrValue;
            }).collect(Collectors.toList());
            roomAttrValueService.saveBatch(roomAttrValueList);
        }

        //3.插入配套信息
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<RoomFacility> roomFacilityList = facilityInfoIds.stream().map(s -> {
                RoomFacility roomFacility = new RoomFacility();
                roomFacility.setRoomId(roomId);
                roomFacility.setFacilityId(s);
                return roomFacility;
            }).collect(Collectors.toList());
            roomFacilityService.saveBatch(roomFacilityList);
        }

        // 4.插入标签信息
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if (!CollectionUtils.isEmpty(labelInfoIds)) {
            List<RoomLabel> roomLabelList = labelInfoIds.stream().map(s -> {
                RoomLabel roomLabel = new RoomLabel();
                roomLabel.setRoomId(roomId);
                roomLabel.setLabelId(s);
                return roomLabel;
            }).collect(Collectors.toList());
            roomLabelService.saveBatch(roomLabelList);
        }
        // 5.插入支付方式信息
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if (!CollectionUtils.isEmpty(paymentTypeIds)) {
            List<RoomPaymentType> roomPaymentTypeList = paymentTypeIds.stream().map(s -> {
                RoomPaymentType roomPaymentType = new RoomPaymentType();
                roomPaymentType.setRoomId(roomId);
                roomPaymentType.setPaymentTypeId(s);
                return roomPaymentType;
            }).collect(Collectors.toList());
            roomPaymentTypeService.saveBatch(roomPaymentTypeList);
        }

        // 6.插入租期信息
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIds)) {
            List<RoomLeaseTerm> roomLeaseTermList = leaseTermIds.stream().map(s -> {
                RoomLeaseTerm roomLeaseTerm = new RoomLeaseTerm();
                roomLeaseTerm.setRoomId(roomId);
                roomLeaseTerm.setLeaseTermId(s);
                return roomLeaseTerm;
            }).collect(Collectors.toList());
            roomLeaseTermService.saveBatch(roomLeaseTermList);
        }
    }


    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private LeaseAgreementService leaseAgreementService;

    /**
     * 根据条件分页查询房间列表
     *
     * @param current
     * @param size
     * @param queryVo
     * @return
     */
    @Override
    public IPage<RoomItemVo> pageItem(long current, long size, RoomQueryVo queryVo) {
        //  创建分页对象
        Page<RoomInfo> page = new Page<>(current, size);
        //先查询满足的公寓信息
        List<ApartmentInfo> list = apartmentInfoMapper.selectList(Wrappers.<ApartmentInfo>lambdaQuery()
                .eq(queryVo.getProvinceId() != null, ApartmentInfo::getProvinceId, queryVo.getProvinceId())
                .eq(queryVo.getCityId() != null, ApartmentInfo::getCityId, queryVo.getCityId())
                .eq(queryVo.getDistrictId() != null, ApartmentInfo::getDistrictId, queryVo.getDistrictId())
                .eq(queryVo.getApartmentId() != null, ApartmentInfo::getId, queryVo.getApartmentId()));
        //获取到满足的公寓id
        Page<RoomInfo> page1 = null;
        List<RoomItemVo> collect1 = null;
        Page<RoomItemVo> roomItemVoPage = null;
        if (!CollectionUtils.isEmpty(list)) {
            Set<Long> collect = list.stream().map(s -> s.getId()).collect(Collectors.toSet());
            page1 = lambdaQuery().in(RoomInfo::getApartmentId, collect).page(page);
            List<RoomInfo> records = page1.getRecords();
            collect1 = records.stream().map(s -> {
                RoomItemVo roomItemVo = new RoomItemVo();
                BeanUtils.copyProperties(s, roomItemVo);
                LeaseAgreement one = leaseAgreementService.lambdaQuery().eq(LeaseAgreement::getRoomId, s.getId())
                        .in(LeaseAgreement::getStatus, 2, 5)
                        .select(LeaseAgreement::getLeaseEndDate, LeaseAgreement::getStatus).one();
//                LeaseStatus status = null;
                roomItemVo.setIsCheckIn(false);
                if (one != null) {
                    roomItemVo.setLeaseEndDate(one.getLeaseEndDate());
                    Integer code = one.getStatus().getCode();
                    roomItemVo.setIsCheckIn(code >= 2 && code <= 5);
                }
                ApartmentInfo apartmentInfo = list.stream().filter(s1 -> s1.getId().equals(s.getApartmentId())).findFirst().get();
                roomItemVo.setApartmentInfo(apartmentInfo);
                return roomItemVo;
            }).collect(Collectors.toList());
            roomItemVoPage = new Page<>();
            roomItemVoPage.setRecords(collect1);
            roomItemVoPage.setTotal(page1.getTotal());
        }
        return roomItemVoPage;
    }



    /**
     * 根据id获取房间详细信息
     *
     * @param id
     * @return
     */
    @Override
    public RoomDetailVo getDetailById(Long id) {
        //创建一个RoomDetailVo
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        //根据id获取房间详细信息
        RoomInfo roomInfo = this.getById(id);
        //进行属性拷贝
        BeanUtils.copyProperties(roomInfo, roomDetailVo);
        //根据id获取所属公寓的信息
        ApartmentInfo apartmentInfo = apartmentInfoMapper.getInfoById(roomInfo.getApartmentId());
        roomDetailVo.setApartmentInfo(apartmentInfo);
        //获取图片列表
        List<GraphInfo> list = graphInfoService.lambdaQuery()
                .eq(GraphInfo::getItemType, ItemType.ROOM)
                .eq(GraphInfo::getItemId, id)
                .select(GraphInfo::getId, GraphInfo::getName, GraphInfo::getUrl)
                .list();
        List<GraphVo> collect = list.stream().map(s -> {
            GraphVo graphVo = new GraphVo();
            BeanUtils.copyProperties(s, graphVo);
            return graphVo;
        }).collect(Collectors.toList());
        roomDetailVo.setGraphVoList(collect);
        //获取属性信息列表
        List<AttrValueVo> attrValueList = roomAttrValueService.getKeyNames(id);
        roomDetailVo.setAttrValueVoList(attrValueList);
        //获取配套信息列表
        List<FacilityInfo> facilityInfoList = roomFacilityService.getFacilityInfo(id);
        roomDetailVo.setFacilityInfoList(facilityInfoList);
        //获取标签信息列表
        List<LabelInfo> labelInfoList = roomLabelService.getLabelInfo(id);
        roomDetailVo.setLabelInfoList(labelInfoList);
        //获取支付方式列表
        List<PaymentType> paymentTypeList = roomPaymentTypeService.getPaymentTypeInfo(id);
        roomDetailVo.setPaymentTypeList(paymentTypeList);
        //获取可租时间列表
        List<LeaseTerm> leaseTermList = roomLeaseTermService.getLeaseTermInfo(id);
        roomDetailVo.setLeaseTermList(leaseTermList);
        return roomDetailVo;
    }
}





